﻿


if COL_LENGTH('ERPStoreOffersOfferedProduct', 'ProductId') is null
Begin
	alter table ERPStoreOffersOfferedProduct add ProductId int null
End
Go

if COL_LENGTH('ERPStoreOffersOfferedProduct', 'OfferId') is null
Begin
	alter table ERPStoreOffersOfferedProduct add OfferId int null
End
Go

if COL_LENGTH('ERPStoreOffersEntitySelectedDetailExtensionId', 'ProductId') is null
Begin

	update ERPStoreOffersOfferedProduct
	Set ProductId = EntitySelectionDetail.InternalEntityId
	from ERPStoreOffersOfferedProduct
		join EntitySelectionDetail on ERPStoreOffersOfferedProduct.ERPStoreOffersEntitySelectedDetailExtensionId = EntitySelectionDetail.Id
	where EntitySelectionDetail.InternalEntityId is not null

	update ERPStoreOffersOfferedProduct
	set OfferId = (select top 1 ERPStoreOffersOffer.Id 
					from EntitySelectionDetail 
						join ERPStoreOffersOffer on EntitySelectionDetail.EntitySelectionId = ERPStoreOffersOffer.ProductSelectionId)
	
End
Go

if COL_LENGTH('ERPStoreOffersOfferedProduct', 'ERPStoreOffersEntitySelectedDetailExtensionId') is not null
Begin
	alter table ERPStoreOffersOfferedProduct drop column ERPStoreOffersEntitySelectedDetailExtensionId
End
Go

if COL_LENGTH('ERPStoreOffersOfferedProduct', 'Id') is null
Begin
	alter table ERPStoreOffersOfferedProduct add Id int identity(1,1) not null
	
	alter table ERPStoreOffersOfferedProduct add constraint PK_ERPStoreOffersOfferedProduct_Id primary key (Id)
End
Go

delete ERPStoreOffersOfferedProduct where productId is null
Go

alter table ERPStoreOffersOfferedProduct alter column ProductId int not null
Go

alter table ERPStoreOffersOfferedProduct alter column OfferId int not null
Go
